package com.admin.service.impl;

import com.admin.common.enums.EnumResult;
import com.admin.common.exception.BizException;
import com.admin.common.util.OssUtils;
import com.admin.service.OssUtilsService;
import com.admin.service.UploadService;
import com.admin.vo.ResultVO;
import com.admin.vo.upload.UploadVO;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Value("${attachment.uploadPath}")
    private String FILE_UPLOAD_PATH;

    @Value("${attachment.prefix}")
    private String FILE_URL;

    @Autowired
    private OssUtilsService ossUtilsService;

    @Override
    public ResultVO<UploadVO> uploadFile(MultipartFile file, String fileType) {
        ResultVO<UploadVO> result = new ResultVO<>();
        String portraitUrl = "";
        UploadVO uploadVO = new UploadVO();
        try {
            String contentType = OssUtils.getContentType(file.getOriginalFilename());
            if (StringUtils.isEmpty(contentType)) {
//                throw new BizException(-1, EnumResult.PARAM_UPLOAD_FORMAT_UNKOWN.getMsg());
            }
            // 1.获取文件流
            MultipartFile imageFile = file;

            //2、设置文件存放目录，文件按月存放，如2022/06
            //TODO 后续文件按类别存放，只需在这里处理即可，如/类别/yyyy/MM
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy");
            String yearDirectory = dateTimeFormatter.format(LocalDateTime.now());

            dateTimeFormatter = DateTimeFormatter.ofPattern("MM");
            String monthDirectory = dateTimeFormatter.format(LocalDateTime.now());

            //3、目录不存在，动态创建
            File directory = new File(FILE_UPLOAD_PATH + yearDirectory + File.separator + monthDirectory);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            String fileName = UUID.randomUUID() + imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf("."));// 文件名

            //4.文件上传
            file.transferTo(new File(directory, fileName));

            //5.将完整地址存入数据库
            portraitUrl = FILE_URL + yearDirectory +File.separator + monthDirectory + File.separator + fileName;// 完整地址

            uploadVO.setUrl(portraitUrl);
            uploadVO.setName(imageFile.getOriginalFilename());

        } catch (IOException e) {
            log.error("上传图片异常：", e);
            throw new BizException(EnumResult.OPERATION_ERROR.getCode(), EnumResult.OPERATION_ERROR.getMsg());
        }
        result.setData(uploadVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }



    @Override
    public ResultVO<UploadVO> uploadFileForOSS(MultipartFile file, String fileType) {
        ResultVO<UploadVO> result = new ResultVO<>();
        String portraitUrl = "";
        UploadVO uploadVO = new UploadVO();
        try {
            String contentType = OssUtils.getContentType(file.getOriginalFilename());
            if (StringUtils.isEmpty(contentType)) {
//                throw new BizException(-1, EnumResult.PARAM_UPLOAD_FORMAT_UNKOWN.getMsg());
            }
            // 1.获取文件流
            MultipartFile imageFile = file;
            String fileName = UUID.randomUUID() + imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf("."));// 文件名
            // 2.上传oss
//            ossUtilsService.upload(imageFile, fileType + "/" + fileName);
            ossUtilsService.uploadNewVersion(imageFile, fileName);
            // 3.将完整地址存入数据库
            portraitUrl = ossUtilsService.getOssUrl() + ossUtilsService.getOssPathChild() + fileName;// 完整地址

            uploadVO.setUrl(ossUtilsService.getSignUrl(portraitUrl));
            uploadVO.setName(imageFile.getOriginalFilename());

        } catch (IOException e) {
            log.error("上传图片异常：", e);
            throw new BizException(EnumResult.OPERATION_ERROR.getCode(), EnumResult.OPERATION_ERROR.getMsg());
        }
        result.setData(uploadVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }





}
